﻿using System.Diagnostics;
using static System.Console;

/*
 * Thread Lock
 */

int sharedCounter = 0;
object lockObject = new object();

// 创建两个线程
Thread t1 = new Thread(IncrementCount);
Thread t2 = new Thread(IncrementCount);
// 启动线程
t1.Start();
t2.Start();

// 等待两个线程执行完毕
t1.Join();
t2.Join();

// 等待最终的计数器值
WriteLine($"Final counter value:{sharedCounter}");


void IncrementCount()
{
    for (int i = 0; i < 100; i++)
    {
        // 使用lock关键字保护共享资源
        lock (lockObject)
        {
            sharedCounter++;
            WriteLine(sharedCounter);
        }
    }
}